<template>
  <view class="container" :style="'width:'+videoPlay.width+';height:'+videoPlay.height+';'">
    <video id="myVideo" class="video" :src="videoPlay.src" :controls="false" :show-center-play-btn="false"
           :enable-progress-gesture="false" @play="videoPlayF" @timeupdate="timeupdate" @ended="Ended" autoplay></video>
    <view class="video-components" :style="videoComponents===false?'height:150%;':''" @click="showVideoComponents">
      <view class="title">
        <view @click="setOrientation" class="title-icon" v-if="videoPlay.palyType===1"><uni-icons size="25" color="#fff" type="back"></uni-icons></view>
        <text>{{videoInfo.titleCus}}</text>
      </view>
      <view v-if="!isPlay" class="play" @click="setPlay"><image :src="image_hosts+(isPlay?'/zanting.png':'/icon_play_pre@2x.png')"></image></view>
      <view class="video-bottom">
        <view class="play-button" @click="setPlay"><image :src="image_hosts+(isPlay?'/zanting1.png':'/icon_play@2x.png')"></image></view>
        <view class="schedule">
          <view class="startTime">{{currentTime}}</view>
          <view class="jindu-box">
            <view class="jindu" :style="'width:'+jindu+'%'"></view>
            <view class="jindu-dian" :style="'left:'+jindu+'%'"></view>
          </view>
          <view class="endTime">{{duration}}</view>
        </view>
        <view class="quanping" @click="setOrientation">
          <image v-if="videoPlay.palyType!==1" :src="image_hosts+'/icon_play_big.png'"></image>
          <image v-if="videoPlay.palyType===1" :src="image_hosts+'/icon_play_small_heng@2x.png'"></image>
        </view>
      </view>
    </view>
    <view class="message-box" v-if="messageBoxShow" :style="messageBoxStyle">
      <text>前方即将出现题目，请认真听讲哦！</text>
      <view class="message-icon"><image :src="image_hosts+'/icon_sp_jushou@2x.png'"></image></view>
      <view class="message-button" @click="messageBoxShow=!messageBoxShow">知道了</view>
    </view>
    <view class="answer-subject-in-progress" v-if="answerSubjectInProgressShow">
      <answer-subject-in-progress :videoInfo="videoInfo" :playingQuestionIndex="playingQuestionIndex" :playingQuestionList="videoInfo.playingQuestionList" @hideAnswerSubjectInProgress="hideAnswerSubjectInProgress" v-if="answerSubjectInProgressShow"></answer-subject-in-progress>
    </view>
    <blessing-bag @sendLuckReward="sendLuckReward" @timeEnd="blessingBagShow=false" :limit="blessingBagConfig.limit" v-if="blessingBagShow"></blessing-bag>
    <blessing-bag-success ref="blessingBagSuccess" v-if="blessingBagSuccessShow" @blessingBagClone="blessingBagClone"></blessing-bag-success>
  </view>
</template>

<script>
import answerSubjectInProgress from "@/pages/newAnswer/components/answer-subject-in-progress.vue";
import blessingBag from "@/pages/newAnswer/components/blessingBag.vue";
import blessingBagSuccess from "@/pages/newAnswer/components/blessingBag-success.vue";
export default {
  components:{answerSubjectInProgress,blessingBag,blessingBagSuccess},
  props:['videoPlay','videoInfo'],
  data() {
    return {
      image_hosts:this.image_host+'videoAnswer',
      currentTime:0,
      duration:0,
      durationValue:0,
      jindu:'',
      isPlay:true,
      videoContext:{},
      videoComponents:true,
      messageBoxStyle:"",
      messageBoxShow:false,
      answerSubjectInProgressShow:false,
      playingQuestionIndex:'',
      answerIndex:'',
      AnswerTime:{},
      progressIndex:0,
      blessingBagShowTime:[
        {time:'',isShow:false},
        {time:'',isShow:false},
        {time:'',isShow:false},
      ],
      blessingBagConfig:{},
      blessingBagShow:false,
      blessingBagSuccessShow:false
    };
  },
  created(){
    console.log(this.videoPlay,'打印')
    this.videoContext = uni.createVideoContext('myVideo',this)
    this.initVideoComponents()
    //#ifdef H5
    this.isPlay=false
    //#endif
    // 获取福袋配置
    this.getBlessingBagConfig()
  },
  watch:{
    durationValue:function (newValue,oleValue){
      // 设置福袋随机生成的时间
      let blessingBagShowTime= uni.getStorageSync("blessingBagShowTime"+this.videoInfo.id) || false;
      if(blessingBagShowTime){
        this.blessingBagShowTime=blessingBagShowTime
      }else {
        this.setBlessingBagShowTime()
      }
    }
  },
  methods:{
    initVideoComponents()
    {
      setTimeout(()=>{
        this.videoComponents=false;
      },5000)
    },
    // 获取福袋配置
    async getBlessingBagConfig()
    {
     let res = await this.$javaCircle.doRequest("get",'vs/ruiVideo/luck/status/'+this.videoInfo.id,{},'');
     this.blessingBagConfig=res.data.data;
      this.blessingBagConfig.getRewardNum=uni.getStorageSync("getRewardNum"+this.videoInfo.id) || this.blessingBagConfig.getRewardNum
     console.log(this.blessingBagConfig)
    },
    // 获取领取阶段
    setBlessingBagShowTime()
    {
      let durationValue=this.durationValue-10
      if(durationValue<60){
        return
      }
      this.blessingBagShowTime[0].time=this.getRandomNumber(60,durationValue<(5*60)?durationValue:5*60);
      // this.blessingBagShowTime[0].time=2;
      this.blessingBagShowTime[1].time=this.getRandomNumber(5*60+1,durationValue<(10*60)?durationValue:10*60);
      this.blessingBagShowTime[2].time=this.getRandomNumber(10*60+1,durationValue>(10*60+1)?durationValue:1000);
      uni.setStorageSync("blessingBagShowTime"+this.videoInfo.id,this.blessingBagShowTime)
      console.log(this.blessingBagShowTime,'福袋出现的位置');
    },
    // 领取福袋
    async sendLuckReward()
    {
      this.setPlay();
      let res = await this.$javaCircle.doRequest("post",'vs/ruiVideo/luck/sendLuckReward?videoId='+this.videoInfo.id,{},'');
      this.blessingBagSuShow(res.data.data.reward)
      this.blessingBagShow=false
    },
    // 关闭成功弹框
    blessingBagClone()
    {
      this.blessingBagSuccessShow=false;
      this.setPlay()
    },
    // 显示弹框
    blessingBagSuShow(num)
    {
      this.blessingBagSuccessShow=true;
      this.$nextTick(()=>{
        this.$refs.blessingBagSuccess.init(num)
      })
    },
    getRandomNumber(start, end) {
      return Math.floor(Math.random() * (end - start + 1)) + start;
    },
    showVideoComponents()
    {
      if(this.videoComponents){
        return
      }
      this.videoComponents=true;
      this.initVideoComponents()
    },
    timeupdate(e){
      const {currentTime,duration} = e.detail
      this.currentTime=this.formatTime(Math.trunc(currentTime));
      this.duration=this.formatTime(Math.trunc(duration));
      this.jindu=this.calculateProgress(duration,currentTime)
      this.durationValue=Math.trunc(duration)
      //播放进度保存
      this.setVideoPlayTime(currentTime)
      //答题中问题弹出
      this.isShowMessage(this.currentTime)
      //设置播放进度
      this.setPlayTime(Math.trunc(currentTime))
      //设置福袋
      this.showBlessingBag(Math.trunc(currentTime))
    },
    // 设置福袋
    showBlessingBag(currentTime)
    {
      let blessingBagConfig=this.blessingBagConfig;
      let blessingBagShowTime = this.blessingBagShowTime;
      let blessingBagShowTimeItem=blessingBagShowTime[blessingBagConfig.getRewardNum];
      /**
       * 1，奖励未领取完
       * 2，不是重复观看
       * 3，待领取个数小于可领取个数
       * 4，当前福袋，未弹出过
       * 5, currentTime 播放时间===设置时间
       */
      if(blessingBagConfig.hasFinish===0 && blessingBagConfig.hasRepeat===0 && blessingBagConfig.getRewardNum<blessingBagConfig.rewardNum && !blessingBagShowTimeItem.isShow && currentTime===blessingBagShowTimeItem.time){
        if(this.blessingBagShowTime[blessingBagConfig.getRewardNum]) {
			this.blessingBagShowTime[blessingBagConfig.getRewardNum].isShow = true;
		}
        this.blessingBagShow=true;
        this.blessingBagConfig.getRewardNum++;
        uni.setStorageSync("getRewardNum"+this.videoInfo.id,this.blessingBagConfig.getRewardNum)
        if(blessingBagConfig.rewardNum===this.blessingBagConfig){
          this.blessingBagConfig.hasRepeat=1
        }
      }else {
        console.log(`当前时间:${currentTime}\n
        hasFinish:${blessingBagConfig.hasFinish}\n
        hasRepeat:${blessingBagConfig.hasRepeat}\n
        getRewardNum:${blessingBagConfig.getRewardNum}\n
        rewardNum:${blessingBagConfig.rewardNum}\n
        blessingBagShowTimeItem.isShow:${blessingBagShowTimeItem.isShow}\n
        出现时间:${blessingBagShowTimeItem.time}
        `)
      }
    },
    formatTime(seconds) {
      const minutes = Math.floor(seconds / 60); // 计算分钟数
      const remainingSeconds = seconds % 60; // 计算剩余的秒数
      const formattedMinutes = String(minutes).padStart(2, '0'); // 格式化分钟数，确保两位数显示
      const formattedSeconds = String(remainingSeconds).padStart(2, '0'); // 格式化秒数，确保两位数显示
      return `${formattedMinutes}:${formattedSeconds}`; // 返回格式化后的分钟:秒钟字符串
    },
    calculateProgress(videoLength, playedLength) {
      const progress = (playedLength / videoLength) * 100; // 计算进度百分比
      return progress.toFixed(2); // 保留两位小数
    },
    setOrientation()
    {
      this.$emit('setOrientation')
    },
    setPlay()
    {
      this.isPlay=!this.isPlay
      if(this.isPlay){
        this.videoContext.play()
        console.log("play")
      }else {
        this.videoContext.pause()
        console.log("pause")
      }
    },
    // 设置播放时间
    setPlayTime(time)
    {
      let storageTime=uni.getStorageSync("videoAnswer:videoTime"+this.videoInfo.id);
      if(storageTime && storageTime>time){
        this.videoContext.seek(storageTime)
      }
    },
    Ended()
    {
      console.log('播放完成')
      uni.setStorageSync("blessingBagShowTime"+this.videoInfo.id,false)
      uni.setStorageSync("getRewardNum"+this.videoInfo.id,false)
      this.$emit("videoEnd")
    },
	//开始上报
  videoPlayF()
	{
		this.$emit("videoPlays")
	},
    isShowMessage(currentTime)
    {
      let playingQuestionList=this.videoInfo.playingQuestionList;
      let videoType=this.videoInfo.appearScene
      if([1,2].includes(videoType) || playingQuestionList.length!==0){
        playingQuestionList.forEach((item,index)=>{
          if(currentTime===this.formatTime(item.questionTime-13)){
            this.showMessage()
          }
          if(currentTime===this.formatTime(item.questionTime)){
            this.$nextTick(()=>{
              if(this.answerSubjectInProgressShow){
                return;
              }
              if(this.progressIndex!==index){
                return;
              }
              this.playingQuestionIndex=index
                this.answerSubjectInProgressShow=true
                this.setPlay()
                this.setAnswerTime()
                this.messageBoxStyle="right:-1000rpx;"
                this.messageBoxShow=false
            })
          }
        })
      }
    },
    showMessage()
    {
      if(this.messageBoxShow) return;
      this.messageBoxShow=true;
      this.$nextTick(()=>{
        this.messageBoxStyle="right:1000rpx;"
      })
    },
    //播放进度保存
    setVideoPlayTime(currentTime)
    {
      let storageTime=uni.getStorageSync("videoAnswer:videoTime"+this.videoInfo.id)
      if(storageTime<Math.trunc(currentTime)){
        uni.setStorageSync("videoAnswer:videoTime"+this.videoInfo.id,Math.trunc(currentTime))
      }
    },
    //答题中问题答案保存
    hideAnswerSubjectInProgress(index){
      uni.setStorageSync('videoAnswer:'+this.videoInfo.id+'-'+this.playingQuestionIndex,index)
      this.answerSubjectInProgressShow=false
      this.progressIndex++
      clearInterval(this.AnswerTime)
      this.setPlay()
    },
    setAnswerTime()
    {
      this.AnswerTime=setInterval(()=>{
        let time = uni.getStorageSync("videoAnswer:time"+'-'+this.videoInfo.id) || 0
        time++
        uni.setStorageSync("videoAnswer:time"+'-'+this.videoInfo.id,time)
      },1000)
    }
  }
}
</script>

<style lang="scss" scoped>
@function tovmin($rpx){//$rpx为需要转换的字号
  @return #{$rpx * 100 / 750}vmin;
}
.container{
  position: relative;
  overflow: hidden;
  transition: all .2s linear;
}
.video{
  width: 100%;
  height: 100%;
}
.video-components{
  width: 100%;
  height: 100%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  transition: all .6s linear;
}
.title{
  font-size: tovmin(36);
  color: #fff;
  font-weight: 500;
  width: 100%;
  height: tovmin(100);
  line-height: tovmin(100);
  box-sizing: border-box;
  padding-left: tovmin(30);
  background: linear-gradient(360deg, rgba(0,0,0,0) 0%, rgba(0,0,0,0.6) 100%);
  display: flex;
  align-items: center;
}
.title text{
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}
.title-icon{
  display: flex;
  align-items: center;
  margin-right: tovmin(20);
}
.play{
  width: tovmin(90);
  height: tovmin(90);
}
.play image{
  width: 100%;
  height: 100%;
}
.video-bottom{
  width: 100%;
  height: tovmin(100);
  background: linear-gradient(180deg, rgba(0,0,0,0) 0%, rgba(0,0,0,0.6) 100%);
  font-size: tovmin(26);
  font-weight: 500;
  color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: border-box;
  padding: 0upx tovmin(30);
}
.play-button{
  width: tovmin(42);
  height: tovmin(42);
  image{
    width: 100%;
    height: 100%;
  }
}
.schedule{
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-sizing: border-box;
  padding: 0 tovmin(42);
}
.jindu-box{
  height: tovmin(6);
  border-radius: tovmin(6);
  flex: 1;
  margin: 0 tovmin(20);
  background-color: rgba(171,157,151,.5);
  position: relative;
}
.jindu{
  width: 0;
  height: 100%;
  border-radius: tovmin(4);
  background-color: rgba(1, 189, 84, .8);
  transition: all .3s linear;
}
.jindu-dian{
  position: absolute;
  top: 50%;
  left: 0;
  width: tovmin(30);
  height: tovmin(30);
  box-sizing: border-box;
  background-color: rgba(1, 189, 84, 1);
  border: tovmin(6) solid rgba(171,157,151,.9);
  border-radius: 50%;
  transform: translate(-50%,-50%);
  transition: all .3s linear;
}
.quanping{
  width: tovmin(80);
  height: tovmin(43);
  image{
    width: 100%;
    height: 100%;
  }
}

.message-box{
  height: tovmin(58);
  width: tovmin(830);
  border-radius: tovmin(29);
  background: linear-gradient(95deg, rgba(233, 101, 0, .6) 0%, rgba(214, 185, 0, .6) 100%);
  position: absolute;
  top: tovmin(30);
  padding: 0 tovmin(20);
  font-size: tovmin(38);
  color: #fff;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  right: tovmin(-800);
  transition: all 13s linear;
  text-align: center;
}
.message-icon{
  width: tovmin(36);
  height: tovmin(34);
  image{
    width: 100%;
    height: 100%;
  }
}
.message-button{
  text-decoration: underline;
}
@media screen and (orientation:landscape){
  .title{
    height: tovmin(120);
    padding-left: tovmin(120);
    line-height: tovmin(120);
  }
  .video-bottom{
    height: tovmin(120);
    padding:0 tovmin(120);
    font-size: tovmin(24);
  }
  .play-button{
    width: tovmin(52);
    height: tovmin(52);
  }
  .quanping{
    width: tovmin(52);
    height: tovmin(52);
  }
  .jindu-box{
    height: tovmin(8);
  }
  .message-box{
    transition: all 13s linear;
  }
}
.answer-subject-in-progress{
  width: 100%;
  height: 100%;
  position: fixed;
  z-index: 10;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
}

</style>
